<template>
  <div>
    <!-- 搜索 -->
    <!-- 考核单审核 -- 车厂-->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="120" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :is-select-column="true"
    >
    if(getAppId() == 'arcfox'){
      <template slot="controls" slot-scope="props">
      <multiuse-button size="small" type="primary"  :click="exportFileBtn.bind()">导出</multiuse-button>
      </template>
    }else{
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :click="tongGuo.bind()">批量通过</multiuse-button>
        <multiuse-button size="small" type="primary"  @click="buoHui()">批量驳回</multiuse-button>
        <multiuse-button size="small" type="primary"  :click="exportFileBtn.bind()">导出</multiuse-button>
      </template>
    }
    </FilterTable>
    <Drawer :visible.sync="visible" :title="'考核单审核'" width="60%" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <xiangqing @close="close" @save="save" :rowData="rowData"></xiangqing>
    </Drawer>
    <BaseDialog :visible.sync="selectDelearFlag" :title="'经销商选择'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <DealerList @close="Delearclose" @save="Delearsave"></DealerList>
    </BaseDialog>
    </BaseDialog>
      <BaseDialog
      :visible.sync="boHuiAdd"
      :title="'驳回原因'"
      width="850px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <boHuiForm @close="closeboHui" @save="saveboHui" :boHuiIds="boHuiIds"> </boHuiForm>
    </BaseDialog>
  </div>
</template>
<script>
  import xiangqing from './xiangqing.vue';
  import boHuiForm from './boHuiForm.vue';
  import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
  import { exportExcelFile } from '@/utils/index';
  import { getListByPage, getPartType,downloadModel,getListForExport,piLiangTongGuo,piLiangBuoHui,exporturl} from '@/api/claim/factory/CheckSheetMaintain';
  import {  getAppId } from '@/assets/js/auth';
  import { dictionary } from '@/utils/dictMixin';
  import moment from "moment";
  export default {
    mixins: [dictionary],
    components: {
      boHuiForm,
      xiangqing,
      DealerList
    },
    data() {
      return {
        dataList: [],
        boHuiAdd: false,
        boHuiIds: [],
        rowData: {},
        visible: false,
        selectDelearFlag: false,
        visibleDrawer: false,
        collapse: true,
        infoId: null,
        topFilterInit: this.topFilterInitFun(),
        flterValue: {}, //参数
        fetchapi: getListByPage,
        columns: this.creatHeader(),
        fetchParams: {assessStatus : 55451002,xhrAbort: true,}, //ipa 接口
        selectedRows: [], //选中经销商
        dialogTitle: '选择车辆',
        visibleAdd: false
      };
    },
    created() {
      if (getAppId() == 'arcfox') {
        this.formList.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543',[55431001])
      }else{
        this.formList.find(x => x.fieldName == 'assessClassify').itemList =this.createDictList('5543')
      }
      this.fetchParams.beginCreatedAt = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
      this.fetchParams.endCreatedAt = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
      this.chuqi();
      this.chuqi2();
    },
    methods: {
      //搜索获取数据
      changeHandle(val) {
        if(!val.beginCreatedAt) {
          this.$notify.warning({ title: '提示信息', message: '考核开始日期不可为空！' });
          return
        }
        if(!val.endCreatedAt) {
          this.$notify.warning({ title: '提示信息', message: '考核结束日期不可为空！' });
          return
        }
        if(getAppId() == 'arcfox') {
          if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
            this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
            return
          }
        } else {
          if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
            this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
            return
          }
        }
        this.fetchParams = Object.assign({}, this.fetchParams, val,{assessStatus : 55451002,xhrAbort: false});
        // this.SELECT();
      },
      //下载模板
      downloadTemplate() {
        this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.exportLoading = true;
          downloadModel().then(res => {
            console.log('666');
            console.log(res);
            exportExcelFile(res, '考核单导入模板');
            this.exportLoading = false;
          });
        });
      },
      // 导出
     async exportFileBtn() {
      let json = Object.assign({}, { CODE: 'CODE_00000155' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
        // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
        // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
        // if(!beginSubmitDate) {
        //   this.$notify.warning({ title: '提示信息', message: '考核开始日期不可为空！' });
        //   return
        // }
        // if(!endSubmitDate) {
        //   this.$notify.warning({ title: '提示信息', message: '考核结束日期不可为空！' });
        //   return
        // }
        // if(getAppId() == 'arcfox') {
        //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
        //     this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
        //     return
        //   }
        // } else {
        //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
        //     this.$notify.warning({ title: '提示信息', message: '考核日期跨度不可超过十二个月！' });
        //     return
        //   }
        // }
        // let obj = Object.assign({}, this.fetchParams, {assessStatus : 55451002,xhrAbort: false});
        // obj.beginCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
        // obj.endCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
        // getListForExport(obj).then(res => {
        //   exportExcelFile(res.data, '考核单信息');
        // });
      },

      //考核类型
      async chuqi() {
        // const res = await getPartType({ type: 5541 });
        // if (res.resultCode == 200) {
        //   this.topFilterInit.find(x => x.fieldName == 'assessType').initialValue = '';
        //   this.topFilterInit.find(x => x.fieldName == 'assessType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
      //考核单状态
      // async chuqi1() {
      //   const res = await getPartType({ type: 5545 });
      //   if (res.resultCode == 200) {
      //     this.topFilterInit.find(x => x.fieldName == 'assessStatus').initialValue = '';
      //     this.topFilterInit.find(x => x.fieldName == 'assessStatus').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      //   }
      // },
      //考核分类
      async chuqi2() {
        // const res = await getPartType({ type: 5543 });
        // if(getAppId()=='arcfox') {
        //   delete res.data[0]
        // }
        // if (res.resultCode == 200) {
        //   this.topFilterInit.find(x => x.fieldName == 'assessClassify').initialValue = '';
        //   this.topFilterInit.find(x => x.fieldName == 'assessClassify').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
        // }
      },
    //批量通过
    // async tongGuo() {
    //   if (this.selectedRows.length > 0) {
    //     let turnOn = true;
    //     let turnOn2 = true;
    //     this.selectedRows.map(x => {
    //       if (x.returnStatus !== 55451004) {
    //         return turnOn = false;
    //       }
    //       if (x.statusStr !== '已通过') {
    //         return turnOn2 = false;
    //       }
    //     });
    //     if (turnOn === true && turnOn2 === true) {

    //       let arr = [];
    //       this.selectedRows.map(x => {
    //         arr.push(x.assessId);
    //       });
    //        this.loading = true;
    //       const res = await piLiangTongGuo({assessIds: arr});
    //       this.fetchParams = {...this.fetchParams};
    //       this.loading = false;
    //     } else {
    //       this.loading = false;
    //       //return this.$notify.warning({title: '提示信息', message: '批量入库不能包含已入库或已装箱状态'});
    //     }
    //   } else {
    //     return this.$notify.warning({title: '提示信息', message: '请选择单据！'});
    //   }

    // },
        //批量启用
    async tongGuo() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.assessId + ',';
        });
        const res = await piLiangTongGuo({ ids: str, assessStatus: '55451004' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行通过！' });
      }
    },
    //批量驳回
     buoHui() {
       if (this.selectedRows.length > 0) {
        this.boHuiIds = [];
        this.selectedRows.map((x) => {
        this.boHuiIds.push({ assessId: x.assessId});
         this.boHuiAdd = true;
        });
      }
      else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行驳回！' });
      }
    },
    saveboHui(val) {
      this.rowData = val;
      this.boHuiAdd = false;
       this.fetchParams = { ...this.fetchParams };
      
    },
    closeboHui() {
      this.boHuiAdd = false;
    },
      //选中
      selectChange(rows) {
        this.selectedRows = rows;
        console.log(this.selectedRows);
      },
      close() {
        this.visible = false;
      },
      chooseOrderNo(val) {
        this.visible = true;
        this.rowData = val;
      },
      save() {
        this.visible = false;
        this.fetchParams = { ...this.fetchParams };
      },
      add() {
        this.visibleAdd = true;
      },
      closeAdd() {
        this.visibleAdd = false;
        this.fetchParams = { ...this.fetchParams };
      },
      saveAdd() {
        this.visibleAdd = false;
        this.fetchParams = { ...this.fetchParams };
      }, //经销商选择页面
      SelectDelear() {
        this.selectDelearFlag = true;
      }, //关闭
      Delearclose() {
        this.selectDelearFlag = false;
      },
      //保存
      Delearsave(obj) {
        this.topFilterInit.map(x => {
          if ('dealerCode' == x.fieldName) {
            x.initialValue = obj[0].dealerCode; //维修工单号返显
          }
        })

        this.selectDelearFlag = false;

      },
      //搜索数据
      topFilterInitFun() {
        return [
          { type: 'INPUT', label: '考核单号', fieldName: 'assessNo', placeholder: '请输入考核单号...', initialValue: '' },
          { type: 'SELECT', label: '考核类型', fieldName: 'assessType', placeholder: '请选择考核类型...', initialValue: '', itemList: this.createDictList('5541'), },
          // { type: 'SELECT', label: '考核单状态', fieldName: 'assessStatus', placeholder: '请选择', initialValue: '', itemList: [] },
          {
            type: 'RANGE_DATE',
            label: '考核日期',
            fieldName: 'beginCreatedAt|endCreatedAt',
            placeholder: '请输入',
            initialValue: [
              moment()
                .startOf('week')
                .format('YYYY-MM-DD HH:mm:ss'),
              moment()
                .endOf('week')
                .format('YYYY-MM-DD HH:mm:ss')
            ],
            rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
          },
          {
            type: 'INPUT',
            label: '经销商代码',
            fieldName: 'dealerCode',
            placeholder: '请输入经销商代码...',
            initialValue: '',
            unitRender: p => {
              return (
                <div>
                <multiuse-button icon="el-icon-search" onClick={() => this.SelectDelear()} />
              </div>
            );
            }
          },
          // { type: 'INPUT', label: '经销商名称', fieldName: 'dealerName', placeholder: '请输入经销商名称...', initialValue: '' },
          { type: 'SELECT', label: '考核分类', fieldName: 'assessClassify', placeholder: '请选择考核分类...', initialValue: '', itemList: [] }
        ];
      },
      //table表头和数据源
      creatHeader() {
        return [
          {
            title: '序号',
            dataIndex: 'index',
            fixed: 'left',
            width: 80,
            sorter: true,
            render: props => {
              return <span>{props.row.index + 1}</span>;
            }
          },
          {
            title: '操作',
            dataIndex: 'column-action',
            width: 80,
            render: (props, h) => {
              return (
                <div style="text-align:center">
                  <multiuse-button size="mini" type="text" disabled={((props.row.assessStatus == '55451003') || (props.row.assessStatus == '55451004') || (props.row.assessStatus == '55451005') || (props.row.assessStatus == '55451001')) ? true : false} onClick={() => this.chooseOrderNo(props.row)}>
                    审核
                  </multiuse-button>
                </div>
              );
            }
          },
          { title: '考核单号', dataIndex: 'assessNo', sorter: true },
          { title: '考核状态', dataIndex: 'statusStr', sorter: true },
          { title: '考核分类', dataIndex: 'assessClassifyStr', sorter: true },
          { title: '考核类型', dataIndex: 'assessTypeStr', sorter: true },
          { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
          { title: '经销商名称', dataIndex: 'dealerName', sorter: true, width: 220 },
          { title: '考核金额', dataIndex: 'assessAmount', sorter: true },
          { title: '考核原因', dataIndex: 'assessReason', sorter: true },
          { title: '备注', dataIndex: 'assessRemarks', sorter: true },
          { title: '考核日期', dataIndex: 'assessDate', sorter: true, dateFormat: 'yyyy-MM-dd'},
          { title: '考核人', dataIndex: 'assessByStr', sorter: true, width: 130 },
          // { title: '主键', dataIndex: 'assessId', sorter: true, hidden: true }
        ];
      }
    }
  };
</script>

<style lang="less" scoped></style>
